package com.ejlchina.tool.fragment

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController
import cn.bingoogolapple.qrcode.core.QRCodeView.Delegate
import com.adolf.androiddemo.databinding.FragmentQrScanBinding
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.constant.REQUEST_FAN_CONTROL_KEY
import com.ejlchina.tool.constant.REQUEST_QR_SCAN_KEY
import com.ejlchina.tool.util.LOG_TAG
import com.ejlchina.tool.util.showToast

class ScanQrFragment: BaseBindingFragment2<FragmentQrScanBinding>(),Delegate {


    //蓝牙连接权限
    private val enableBluetoothConnect = registerForActivityResult(ActivityResultContracts.RequestPermission()) { result ->
        if (result){
            binding.zbarview.startCamera()
            binding.zbarview.startSpot()
        } else {
            showToast("相机权限被拒绝")
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.zbarview.setDelegate(this)
        setHeadVisibility(View.GONE)
        enableBluetoothConnect.launch(Manifest.permission.CAMERA)
    }
    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentQrScanBinding {
        return FragmentQrScanBinding.inflate(inflater,container,true)
    }

    override fun onStart() {
        super.onStart()

    }


    override fun onDestroyView() {
        binding.zbarview.onDestroy()
        super.onDestroyView()
    }
    override fun onScanQRCodeSuccess(result: String?) {
        binding.zbarview.stopSpot();
        binding.zbarview.startCamera()
        result?.let {
            val bundle = bundleOf(BUNDLE_QR_SCAN to splitQrResultToDeviceNo(it))
            requireActivity().supportFragmentManager.setFragmentResult(REQUEST_QR_SCAN_KEY,bundle)
            findNavController().navigateUp()
        }

    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {

    }

    private fun splitQrResultToDeviceNo(result: String): String{
        return result.substringAfterLast("/").substringBefore("&")
    }

    override fun onScanQRCodeOpenCameraError() {
        Log.e(LOG_TAG, "无相机权限,打开相机出错");
    }

    override fun initOnCreateView() {
        super.initOnCreateView()
        setActionBarPadding(false)
    }
}